<?php

/**
 * Class LoginForm
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @package backend.models
 * @since 1.0
 */
class LoginForm extends CFormModel
{
	/**
	 * @var string
	 */
	public $username;

	/**
	 * @var string
	 */
	public $password;

	/**
	 * @var string
	 */
	public $verifyCode;

	/**
	 * @var bool 记住我
	 */
	public $rememberMe;

	/**
	 * @var CUserIdentity
	 */
	private $_identity;

	public function rules()
	{
		return array(
			array('username, password', 'required'),
			array('rememberMe', 'boolean'),
			array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements()),
			array('password', 'authenticate'),
		);
	}

	public function attributeLabels()
	{
		return array(
			'username' => '用户名',
			'password' => '密码',
			'rememberMe' => '记住我',
			'verifyCode' => '验证码',
		);
	}

	public function authenticate($attribute, $params)
	{
		if (!$this->hasErrors()) {
			$this->_identity = new BUserIdentity($this->username, $this->password);
			if (!$this->_identity->authenticate()) {
				Yii::app()->watchdog->write('user_login_fail', '%username 登录失败', array('%username'=>$this->username));
				if ($this->_identity->errorCode == BUserIdentity::ERROR_ROLE_NOT_ALLOW) {
					$this->addError('username', '无效的用户角色');
				} elseif ($this->_identity->errorCode == BUserIdentity::ERROR_USER_NOT_ACTIVATED) {
					$this->addError('username', '用户未激活验证');
				} elseif ($this->_identity->errorCode == BUserIdentity::ERROR_USER_BLOCK) {
					$this->addError('username', '用户已被禁用');
				} else {
					$this->addError('password', '无效的用户名或密码');
				}
			}
		}
	}

	/**
	 * @return bool
	 */
	public function login()
	{
		if ($this->_identity === null) {
			$this->_identity = new BUserIdentity($this->username, $this->password);
			$this->_identity->authenticate();
		}

		if ($this->_identity->errorCode === BUserIdentity::ERROR_NONE) {
			$duration = $this->rememberMe ? 3600 * 24 * 30 : 0; //30天
			Yii::app()->getUser()->login($this->_identity, $duration);
			return true;
		} else {
			return false;
		}
	}
}